// API配置
const API_BASE = 'http://localhost:3000/api';

// 状态管理
let todos = [];
let currentEditId = null;

// DOM元素
const todoList = document.getElementById('todoList');
const emptyState = document.getElementById('emptyState');
const searchInput = document.getElementById('searchInput');
const filterStatus = document.getElementById('filterStatus');
const addBtn = document.getElementById('addBtn');
const modal = document.getElementById('modal');
const modalTitle = document.getElementById('modalTitle');
const todoInput = document.getElementById('todoInput');
const saveBtn = document.getElementById('saveBtn');
const cancelBtn = document.getElementById('cancelBtn');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    loadTodos();
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    // 搜索和筛选
    searchInput.addEventListener('input', debounce(filterTodos, 300));
    filterStatus.addEventListener('change', filterTodos);
    
    // 模态框操作
    addBtn.addEventListener('click', () => openModal());
    cancelBtn.addEventListener('click', closeModal);
    saveBtn.addEventListener('click', saveTodo);
    
    // 键盘事件
    todoInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') saveTodo();
    });
    
    // 点击模态框外部关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) closeModal();
    });
}

// 加载待办事项
async function loadTodos() {
    try {
        const response = await fetch(`${API_BASE}/todos`);
        todos = await response.json();
        renderTodos();
    } catch (error) {
        console.error('加载待办事项失败:', error);
        showNotification('加载失败，请检查网络连接', 'error');
    }
}

// 渲染待办事项列表
function renderTodos() {
    const filteredTodos = getFilteredTodos();
    
    if (filteredTodos.length === 0) {
        todoList.innerHTML = '';
        emptyState.classList.remove('hidden');
        return;
    }
    
    emptyState.classList.add('hidden');
    todoList.innerHTML = filteredTodos.map(todo => `
        <div class="todo-item bg-white rounded-lg shadow-md p-4 fade-in" data-id="${todo.id}">
            <div class="flex items-center justify-between">
                <div class="flex items-center flex-1">
                    <input type="checkbox" ${todo.completed ? 'checked' : ''} 
                           onchange="toggleTodo(${todo.id}, ${!todo.completed})"
                           class="mr-3 h-5 w-5 text-blue-600 rounded focus:ring-blue-500">
                    <span class="todo-title ${todo.completed ? 'text-gray-500' : 'text-gray-800'}">
                        ${escapeHtml(todo.title)}
                    </span>
                </div>
                <div class="flex gap-2">
                    <button onclick="editTodo(${todo.id})" 
                            class="action-btn text-blue-500 hover:text-blue-700">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button onclick="deleteTodo(${todo.id})" 
                            class="action-btn text-red-500 hover:text-red-700">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
            <div class="text-xs text-gray-400 mt-2">
                ${formatDate(todo.created_at)}
            </div>
        </div>
    `).join('');
}

// 获取筛选后的待办事项
function getFilteredTodos() {
    const searchTerm = searchInput.value.toLowerCase();
    const statusFilter = filterStatus.value;
    
    return todos.filter(todo => {
        const matchesSearch = todo.title.toLowerCase().includes(searchTerm);
        const matchesStatus = statusFilter === '' || 
                            (statusFilter === 'true' && todo.completed) || 
                            (statusFilter === 'false' && !todo.completed);
        
        return matchesSearch && matchesStatus;
    });
}

// 切换待办事项状态
async function toggleTodo(id, completed) {
    try {
        const response = await fetch(`${API_BASE}/todos/${id}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ completed })
        });
        
        if (response.ok) {
            const updatedTodo = await response.json();
            const index = todos.findIndex(t => t.id === id);
            todos[index] = updatedTodo;
            renderTodos();
        }
    } catch (error) {
        console.error('更新状态失败:', error);
        showNotification('更新失败，请重试', 'error');
    }
}

// 编辑待办事项
function editTodo(id) {
    const todo = todos.find(t => t.id === id);
    if (todo) {
        currentEditId = id;
        modalTitle.textContent = '编辑待办事项';
        todoInput.value = todo.title;
        openModal();
    }
}

// 删除待办事项
async function deleteTodo(id) {
    if (!confirm('确定要删除这个待办事项吗？')) return;
    
    try {
        const response = await fetch(`${API_BASE}/todos/${id}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            todos = todos.filter(t => t.id !== id);
            renderTodos();
            showNotification('删除成功', 'success');
        }
    } catch (error) {
        console.error('删除失败:', error);
        showNotification('删除失败，请重试', 'error');
    }
}

// 打开模态框
function openModal() {
    modal.classList.remove('hidden');
    todoInput.focus();
}

// 关闭模态框
function closeModal() {
    modal.classList.add('hidden');
    currentEditId = null;
    todoInput.value = '';
    modalTitle.textContent = '添加待办事项';
}

// 保存待办事项
async function saveTodo() {
    const title = todoInput.value.trim();
    
    if (!title) {
        showNotification('请输入待办事项内容', 'error');
        return;
    }
    
    try {
        if (currentEditId) {
            // 编辑模式
            const response = await fetch(`${API_BASE}/todos/${currentEditId}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ title })
            });
            
            if (response.ok) {
                const updatedTodo = await response.json();
                const index = todos.findIndex(t => t.id === currentEditId);
                todos[index] = updatedTodo;
                showNotification('更新成功', 'success');
            }
        } else {
            // 新增模式
            const response = await fetch(`${API_BASE}/todos`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ title })
            });
            
            if (response.ok) {
                const newTodo = await response.json();
                todos.unshift(newTodo);
                showNotification('添加成功', 'success');
            }
        }
        
        closeModal();
        renderTodos();
    } catch (error) {
        console.error('保存失败:', error);
        showNotification('保存失败，请重试', 'error');
    }
}

// 筛选待办事项
function filterTodos() {
    renderTodos();
}

// 工具函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 px-4 py-2 rounded-lg text-white ${
        type === 'success' ? 'bg-green-500' : 
        type === 'error' ? 'bg-red-500' : 'bg-blue-500'
    }`;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.remove();
    }, 3000);
}
